import axios from 'axios'
import {
  getToken
} from '@/libs/util.js'
import config from '@/config'

const title = process.env.VUE_APP_TITLE
const env = process.env.NODE_ENV
const baseUrl = getBaseUrl()

function getBaseUrl() {
  switch (env) {
    case 'development': {
      if (title === 'test') {
        return config.baseUrl.test
      } else if (title === 'mock') {
        return config.baseUrl.mock
      } else {
        return config.baseUrl.dev
      }
    }
    case 'production': {
      if (title === 'test') {
        return config.baseUrl.test
      } else if (title === 'mock') {
        return config.baseUrl.mock
      } else {
        return config.baseUrl.pro
      }
    }
  }
}





// 创建axios实例
const service = axios.create({
  baseURL: baseUrl, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // 请求超时时间

  /***
   * 自定义响应成功的HTTP状态码
   * 此时设置成功状态码是2/3开头的状态码，2、3开头会进入成功的响应拦截
   */

  // validateStatus: status => {
  //   return /^(2|3)\d{2}$/.test(status)
  // }
})





// 请求拦截
service.interceptors.request.use(config => {
  config.headers['Authorization'] = getToken()
  return config
}, error => {
  return Promise.reject(error)
})



// 响应拦截
service.interceptors.response.use(res => {
  const {
    data,
    status
  } = res
  return {
    data,
    status
  }
}, error => {
  let errorInfo = error.response
  if (!errorInfo) {
    const {
      request: {
        statusText,
        status
      },
      config
    } = JSON.parse(JSON.stringify(error))
    errorInfo = {
      statusText,
      status,
      request: {
        responseURL: config.url
      }
    }
  }

  if (errorInfo.status === 404) {
    router.push({
      name: 'error_404'
    })
  } else if (errorInfo.status === 500) {
    router.push({
      name: 'error_500'
    })
  } else if (errorInfo.status === 302) {
    // Modal.error({
    //   content: '登录失效，请重新登录',
    //   onOk: () => {
    //     store.dispatch('forceLogOut').then(res => {
    //       top.location.reload()
    //     })
    //   }
    // })
  }

  return Promise.reject(error)
})


export default service
